package com.juyu.miliao.scheduler.message;

import com.juyu.miliao.common.constant.QuestionAndAnswerInfoRedisKey;
import com.juyu.miliao.common.constant.QuestionAndAnswerRabbitMqInfo;
import com.juyu.miliao.scheduler.dao.mysql.QuestionAndAnswerInfoDao;
import com.juyu.miliao.scheduler.dao.mysql.QuestionBillInfoDao;
import com.juyu.miliao.scheduler.dao.mysql.UserWalletDao;
import com.juyu.miliao.scheduler.domin.QuestionAndAnswerInfo;
import com.juyu.miliao.scheduler.domin.QuestionBillInfo;
import com.juyu.miliao.scheduler.domin.UserWallet;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

/**
 * @author xuanqicheng
 * @create 2018-21-9:42 AM
 */
@Component
public class QuestionAndAnswerMessage {

    private final Logger logger = LoggerFactory.getLogger("questionAndAnswerLog");

    @Autowired
    private QuestionAndAnswerInfoDao questionAndAnswerInfoDao;

    @Autowired
    private QuestionBillInfoDao questionBillInfoDao;

    @Autowired
    private UserWalletDao userWalletDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(QuestionAndAnswerRabbitMqInfo.DEAD_QUEUE),
            exchange = @Exchange(QuestionAndAnswerRabbitMqInfo.DEAD_EXCHANGE),
            key = {QuestionAndAnswerRabbitMqInfo.DEAD_ROUTING_KEY}))
    public void getPayInfo(String message) {
        try {

            long questionId = Long.parseLong(message);
            /**
             * 根据id查询没有被回答的信息
             */
            QuestionAndAnswerInfo questionAndAnswerInfo = questionAndAnswerInfoDao.selectInfoExpireById(questionId);

            if (questionAndAnswerInfo != null) {
                //问题还没被回答，将问题变成过期，并退还金币，生成账单
                QuestionAndAnswerInfo obj = new QuestionAndAnswerInfo();

                obj.setId(questionAndAnswerInfo.getId());
                //设置问题状态为过期
                obj.setQuestionStatus(3);

                questionAndAnswerInfoDao.updateQuestionAndAnswerExpire(obj);

                //退款
                UserWallet entity = new UserWallet();

                entity.setUserId(questionAndAnswerInfo.getQuestionUserId());

                entity.setDeposit(10);

                // 减提问者金币
                userWalletDao.reviseDeposit(entity);


                logger.info("[判断主播是否回答问题]用户：{}提问的问题{}没有被回答退回金币10个", questionAndAnswerInfo.getQuestionUserId()
                        , questionAndAnswerInfo.getId());

                //生成账单
                QuestionBillInfo questionBillInfo = questionBillInfoDao.selectQuestionBillById(questionId);

                LocalDateTime expritTime = LocalDateTime.now();

                questionBillInfo.setRefundTime(expritTime);

                questionBillInfo.setStatus(3);

                String sqlKey = "updateQuestionBillByExpire";

                questionBillInfoDao.updateInfo(sqlKey, questionBillInfo);

                //发送消息

                //刷新缓存

            }
        } catch (Exception ex) {
            logger.error("[判断主播是否回答问题]错误:"+ex.getMessage());
        }
    }

    /**
     * 更新问答缓存
     * @param message, 问题id
     */
    @RabbitListener(bindings = @QueueBinding(value = @Queue(QuestionAndAnswerRabbitMqInfo
            .QUEUE_TO_QUESTION_ANSWER_ID_QUEUE),
            exchange = @Exchange(QuestionAndAnswerRabbitMqInfo.EXCHANGE_TO_UPDATE_QUESTION_ANSWER),
            key = {QuestionAndAnswerRabbitMqInfo.ROUTING_KEY_TO_UPDATE_QUESTION_ANSWER}))
    public void getUpdateQuestion(String message) {
        try {
            logger.info("[更新用户问答缓存]更新缓存:{}",message);

            Set<String> deletKeySet = new HashSet<>();

            String questionAndAnswerInfoByQuestionIdKey = QuestionAndAnswerInfoRedisKey
                    .QuestionAndAndwserInfoByQuestionIdEnum.REDIS_KEY.getKeyFormat(message);

            deletKeySet.add(questionAndAnswerInfoByQuestionIdKey);

            String highQualityKey=QuestionAndAnswerInfoRedisKey.QuestionAndAndwserByHighQuality.REDIS_KEY.getKeyFormat();

            deletKeySet.add(highQualityKey);

            stringRedisTemplate.delete(deletKeySet);

            logger.info("[更新用户问答缓存]共跟新缓存：{}个",deletKeySet.size());

        } catch (Exception ex) {
            logger.error("[更新用户问答缓存]错误:"+ex.getMessage());
        }
    }

}
